package com.spring.cootask.web.service.impl;

import com.spera.shopoa.util.PoiExcelUtils;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spring.basetype.web.model.BaseType;
import com.spring.cootask.web.dao.*;
import com.spring.cootask.web.model.*;
import com.spring.cootask.web.service.CooTaskTableService;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.MyTools;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by WoJunyu on 2016/9/6.
 */
@Service
public class CooTaskTableServiceImpl implements CooTaskTableService{

    @Resource
    private CooTaskTableMapper cooTaskTableMapper;
    
    @Resource
    private TaskTablebaseMapper taskTablebaseMapper;
    
    @Resource
    private TaskTablebaseDetailMapper taskTablebaseDetailMapper;

    @Override
    public List<CooTaskTable> selectByParm(Map<String, Object> parm) {
        return cooTaskTableMapper.selectByParm(parm);
    }

    @Override
    public BaseResult saveTable(CooTaskTable data,ShopOaSessionUtil.OaUser oaUser) throws  Exception{
        BaseResult ret = new BaseResult();
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            ret.setStatus("0");
            ret.setMsg("请先登录");
            return ret;
        }
        int i;
        if(ApplicationUtils.isNotNull(data.getId())){//修改
            data.setChangedtime(new Date());
            data.setOperatorid(oaUser.getOa_user_id());
            data.setOperatorname(oaUser.getOa_user_name());
            i = cooTaskTableMapper.updateByPrimaryKeySelective(data);
        }else{//新增
            String id = ApplicationUtils.randomUUID();
            data.setId(id);
            data.setColumnCode("col_"+id.replaceAll("-",""));
            data.initInfo();
            data.setInitialoperatorid(oaUser.getOa_user_id());
            data.setInitialoperatorname(oaUser.getOa_user_name());
            i = cooTaskTableMapper.insert(data);
        }
        if(i==0){
            ret.setStatus("0");
            ret.setMsg("保存失败");
        }
        return ret;
    }

    @Override
    public BaseResult deleteTable(String id)  throws  Exception{
        BaseResult ret = new BaseResult();
        int i = cooTaskTableMapper.deleteByPrimaryKey(id);
        if(i==0){
            ret.setStatus("0");
            ret.setMsg("删除失败");
        }
        return ret;
    }
    
	@Override
	public List<TaskTablebase> tablebase() {
		return taskTablebaseMapper.select();
	}
	
	@Override
	public BaseResult saveOrUpdateTablebase(TaskTablebase tb) throws Exception {		
		int effect=0;
		
		if(MyTools.checkIsNull(tb.getId())){
			effect=taskTablebaseMapper.insert(tb);
		}else{
			effect=taskTablebaseMapper.updateByPrimaryKeySelective(tb);		
		}				
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult deltablebase(String id) throws Exception {	
		
		//taskTablebaseDetailMapper.deleteByTablebaseID(id);
		
		TaskTablebase taskTablebase=new TaskTablebase();
		taskTablebase.setId(id);
		taskTablebase.setEntityavailablestate(20);
		
		//int effect = taskTablebaseMapper.deleteByPrimaryKey(id);
		int effect = taskTablebaseMapper.updateByPrimaryKeySelective(taskTablebase);
	
		return MyTools.checkResult(effect);
	}
	
	
	@Override
	public List<TaskTablebaseDetail> tablebasedetail(String tablebaseID) {
		return taskTablebaseDetailMapper.selectByTablebaseID(tablebaseID);
	}
	
	@Override
	public BaseResult tablebasedetail(TaskTablebaseDetail ttd) throws Exception {		
		int effect=0;
		
		if(MyTools.checkIsNull(ttd.getId())){
			effect=taskTablebaseDetailMapper.insert(ttd);
		}else{
			effect=taskTablebaseDetailMapper.updateByPrimaryKeySelective(ttd);	
		}				
		return MyTools.checkResult(effect);
	}
	
	@Override
	public BaseResult deltablebasedetail(String id) throws Exception {
        String[] idArr = id.split(",");
        int effect = 0;
        for(String oneId:idArr){
            effect=taskTablebaseDetailMapper.deleteByPrimaryKey(oneId);
        }
		return MyTools.checkResult(effect);
	}

    @Override
    public BaseResult importExcel(String id, MultipartFile excel) throws Exception {
        BaseResult br = new BaseResult();
        Workbook book = null;
        book = new HSSFWorkbook(excel.getInputStream());
        Sheet sheet = sheet = book.getSheetAt(0);
//            System.out.println("sheet名称是："+sheet.getSheetName());
        int lastRowNum = sheet.getLastRowNum();
        List<TaskTablebaseDetail> colList = new ArrayList<TaskTablebaseDetail>();
//            System.out.println(lastRowNum+","+sheet.getColumnWidth(0));
        int sort = 1;
        TaskTablebaseDetail ttd = new TaskTablebaseDetail();
        ttd.initInfo();
        ttd.setfTaskTablebaseid(id);
        for(int i=2;i<=lastRowNum;i++){
            Row row = sheet.getRow(i);
            //默认第一列为行字段
            Cell cell =row.getCell(0);
            if(cell != null){
                int type = cell.getCellType();
                String value = "";
                switch (type) {
                    case 1:
                        value = cell.getStringCellValue();
                        break;
                    case 5:
                        byte b = cell.getErrorCellValue();
                        value = String.valueOf(b);
                        break;
                    default:
                        break;
                }
                if(ApplicationUtils.isNotNull(value)){
                    String uuid = ApplicationUtils.randomUUID();
                    ttd.setId(uuid);
                    ttd.setColumnCode("col_" + uuid.replaceAll("-", ""));
                    ttd.setName(value);
                    ttd.setSort(sort);
                    ttd.setType(0);//字符串
                    ttd.setItemType(0);//横向
//                System.out.println(value);
                    taskTablebaseDetailMapper.insert(ttd);
                    sort++;
                }
            }
        }
        //默认第二行为设置列字段
        Row row = sheet.getRow(1);
        int lastCellNum = row.getLastCellNum();
        //获取列字段，此处省去第一格，已在项目列保存
        for(int j=1;j<lastCellNum;j++){
            Cell cell = row.getCell(j);
            if(cell != null){
                int type = cell.getCellType();
                String value = "";
                switch (type) {
                    case 1:
                        value = cell.getStringCellValue();
                        break;
                    case 5:
                        byte b = cell.getErrorCellValue();
                        value = String.valueOf(b);
                    default:
                        break;
                }
                if(ApplicationUtils.isNotNull(value)) {
                    String uuid = ApplicationUtils.randomUUID();
                    ttd.setId(uuid);
                    ttd.setColumnCode("col_" + uuid.replaceAll("-", ""));
                    ttd.setName(value);
                    ttd.setSort(sort);
                    ttd.setType(0);//字符串
                    ttd.setItemType(1);//纵向
//                System.out.println(value);
                    taskTablebaseDetailMapper.insert(ttd);
                    sort++;
                }
            }
        }

        return br;
    }
}
